<template>
  <!-- 表单上部按钮 -->
  <div class="btn">
    <div class="batch_btn">
      <a-button type="primary" :disabled="!hasSelected" @click="ChangeOperation(40001)"> 批量发布 </a-button>
      <a-button type="primary" :disabled="Deactivate" @click="ChangeOperation(40002)"> 批量停用 </a-button>
    </div>
    <a-button type="primary" class="op_btn" @click="addSourceBase(0)">新增数据源</a-button>
  </div>
  <a-table
    :columns="columns"
    :data-source="data"
    :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, preserveSelectedRowKeys: true }"
    :row-key="(record:any) => record.id"
    :locale="{
      cancelSort: '点击取消排序',
      triggerAsc: '点击升序',
      triggerDesc: '点击降序',
    }"
    :loading="loading"
    :pagination="pageOptions"
  >
    <template #bodyCell="{ column, record }">
      <!-- 数据库类型 -->
      <template v-if="column.dataIndex === 'dtName'">
        <a-tag color="#2db7f5">{{ record.dtName }}</a-tag>
      </template>
      <!-- 连接信息 -->
      <template v-if="column.dataIndex === 'dsmConnectInfo'">
        <a-tag>{{ record.dsmConnectInfo }}</a-tag>
      </template>
      <!-- 状态 -->
      <template v-if="column.dataIndex === 'dsmStatus'">
        <a-tag :color="record.statusColor">{{ record.dsmStatus }}</a-tag>
      </template>
      <!-- 操作 -->
      <template v-else-if="column.dataIndex === 'options'">
        <div style="display: flex">
          <a-button type="link" @click="connectTest(record)">连通测试</a-button>
          <!-- 未发布 -->
          <span v-show="record.dsmStatus === '未发布'" class="list_btn">
            <a-popconfirm placement="topRight" ok-text="是" cancel-text="否" @confirm="releaseOrOutage(record, 40001)">
              <template #title>
                <p>是否将应用状态更改为发布</p>
              </template>
              <a-button type="link">发布</a-button>
            </a-popconfirm>

            <a-button type="link" @click="addSourceBase(1, record)">编辑</a-button>

            <a-popconfirm placement="topRight" ok-text="是" cancel-text="否" @confirm="delDatabase(record.id)">
              <template #title>
                <p>是否删除数据源</p>
              </template>
              <a-button type="link" danger>删除</a-button>
            </a-popconfirm>
          </span>
          <!-- 已发布 -->
          <span v-show="record.dsmStatus === '已发布'" class="list_btn">
            <a-popconfirm placement="topRight" ok-text="是" cancel-text="否" @confirm="releaseOrOutage(record, 40002)">
              <template #title>
                <p>是否将应用状态更改为停用</p>
              </template>
              <a-button type="link" danger>停用</a-button>
            </a-popconfirm>
          </span>
          <!-- 已停用 -->
          <span v-show="record.dsmStatus === '已停用'" class="list_btn">
            <a-popconfirm placement="topRight" ok-text="是" cancel-text="否" @confirm="releaseOrOutage(record, 40001)">
              <template #title>
                <p>是否将应用状态更改为发布</p>
              </template>
              <a-button type="link">发布</a-button>
            </a-popconfirm>
            <a-button type="link" @click="addSourceBase(1, record)">编辑</a-button>
          </span>
        </div>
      </template>
    </template>
  </a-table>
</template>
<script lang="ts" setup>
  import { changeDataBaseState, deleteDataBase, postConnectTest } from '@/api/test/index';
  import { addingDataSourcesHooks } from '@/hooks/DatabaseManagementHooks/addingDataSourcesHooks';
  import { getDataBaseListHooks } from '@/hooks/DatabaseManagementHooks/getDataBaseListHooks';
  import { Key, operationStatus } from '../../CodeTables/specification';
  const columns = [
    {
      title: '数据源名称',
      dataIndex: 'dsmName',
      align: 'center',
      width: '10%',
    },
    {
      title: '数据库类型',
      dataIndex: 'dtName',
      align: 'center',
    },
    {
      title: '数据源描述',
      dataIndex: 'dsmDescribe',
      align: 'center',
    },
    {
      title: '连接信息',
      dataIndex: 'dsmConnectInfo',
      align: 'center',
    },
    {
      title: '应用状态',
      dataIndex: 'dsmStatus',
      align: 'center',
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      align: 'center',
      sorter: {
        compare: (a: any, b: any) => (a.updateTime > b.updateTime ? 1 : -1),
        multiple: 3,
      },
      sortDirections: ['ascend', 'descend'],
    },
    {
      title: '操作',
      dataIndex: 'options',
      align: 'center',
    },
  ];
  // 移入hooks
  const { databaseDrawer, dataBase } = addingDataSourcesHooks();
  const { tableData, data, loading, getList } = getDataBaseListHooks();
  // 打开新增--编辑弹窗
  const addSourceBase = (e: number, record?: any) => {
    if (e == 1 && record != undefined) {
      dataBase.dtCode = record.dtCode; //数据库类型
      dataBase.dsmName = record.dsmName; //数据源名称
      dataBase.dsmDescribe = record.dsmDescribe; //数据源描述
      dataBase.dsmConnectInfo = record.dsmConnectInfo; //JDBC URL
      dataBase.dsmDriverName = record.dsmDriverName; //驱动类名
      dataBase.dsmUsername = record.dsmUsername; //用户名
      dataBase.dsmPassword = record.dsmPassword; //密码
    } else {
      dataBase.dtCode = ''; //数据库类型
      dataBase.dsmName = ''; //数据源名称
      dataBase.dsmDescribe = ''; //数据源描述
      dataBase.dsmConnectInfo = ''; //JDBC URL
      dataBase.dsmDriverName = ''; //驱动类名
      dataBase.dsmUsername = ''; //用户名
      dataBase.dsmPassword = ''; //密码
    }
    databaseDrawer.value = true;
  };

  // 第几行是否被选择
  const selectedRowKeys = ref<Key[]>([]);
  // 保存选择后的数据---需要向后端传递的数据
  const selectStopwatch = ref<Object[]>([]);
  // 按钮是否禁用
  const hasSelected = computed(() => selectedRowKeys.value.length > 0);
  const Deactivate = ref<boolean>(true);
  // 监听被选中的列表状态
  watch(
    () => selectStopwatch.value,
    nv => {
      Deactivate.value = false;
      if (nv.length == 0) {
        Deactivate.value = true;
      } else {
        nv.forEach((item: { [arg: string]: any }) => {
          if (item.dsmStatus == '未发布') {
            Deactivate.value = true;
          }
        });
      }

      console.log(' Deactivate.value ' + Deactivate.value);
    },
    { deep: true },
  );
  // 勾选后将勾选数据插入数组
  const onSelectChange = (e: Key[], record: Key[]) => {
    console.log('selectedRowKeys changed: ', e);
    console.log(`${e}-- ${JSON.stringify(record)}`);
    selectedRowKeys.value = e;
    selectStopwatch.value = record;
    console.log(`${JSON.stringify(selectedRowKeys.value)}--${JSON.stringify(selectStopwatch.value)}`);
  };
  //批量按钮操作
  const ChangeOperation = async (e: 40001 | 40002) => {
    loading.value = true;
    const deliverInfo: operationStatus = {
      status: e,
      codeList: selectedRowKeys.value as [string],
    };
    const res = await changeDataBaseState(deliverInfo);
    console.log(res);
    tableData.pageNum = 1;
    getList();
    selectedRowKeys.value = [];
    selectStopwatch.value = [];
  };

  // 发布--停用
  const releaseOrOutage = async (e: any, status: 40001 | 40002) => {
    const deliverInfo: operationStatus = {
      status: status,
      codeList: [e.id],
    };
    const res = await changeDataBaseState(deliverInfo);
    console.log(res);
    tableData.pageNum = 1;
    getList();
  };
  // 分页
  const pageOptions = computed(() => {
    return {
      total: tableData.total,
      current: tableData.pageNum,
      pageSize: tableData.pageSize,
      defaultPageSize: 10,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '30'],
      showQuickJumper: true,
      showTotal: () => `共${tableData.total}条`,
      onChange: (pageNum: number, pageSize: number) => {
        tableData.pageNum = pageNum;
        tableData.pageSize = pageSize;
        getList();
      },
    };
  });
  // 删除按钮
  const delDatabase = async (id: string) => {
    loading.value = true;
    console.log(`删除${id}`);
    await deleteDataBase(id);
    getList();
  };
  // 连通测试
  const connectTest = (e: any) => {
    postConnectTest(e);
  };
</script>

<style lang="less" scoped>
  :deep .ant-table-thead > tr > th {
    font-weight: 600;
    background: rgb(238, 238, 238);
  }

  :deep(.ant-table-content) {
    overflow-y: auto;
    height: calc(100vh - 335px);
    box-shadow: inset 0 -20px 20px -20px #9e9e9e57;

    :deep(.ant-table-row) {
      height: 100px;
    }
  }

  .btn {
    display: flex;
    justify-content: space-between;
    margin: 20px 0px;

    .batch_btn {
      display: flex;
      justify-content: space-evenly;
      width: 20%;
    }

    .op_btn {
      display: flex;
      justify-content: space-evenly;
      margin-right: 2%;
      width: 120px;
    }
  }

  .list_btn {
    display: flex;
    flex-wrap: wrap;

    .ant-btn {
      padding: 5px;
    }
  }
</style>
